package com.huangfu.learning.javabase.java.reflect;

/**
 * Created with IntelliJ IDEA.
 * Author: huangfu.daohui
 * Date: 2018/7/12
 * Time: 19:17
 * Version: 1.0
 * Description: 在这个类中去实例化其他的类
 **/
public class InstenceOtherClass {

    //大家以后再编写使用Class实例化其他类的对象的时候，一定要自己定义无参的构造函数。
    // 否则报错
    public InstenceOtherClass() {

    }

    public InstenceOtherClass(String name, int age) {
        this.name = name;
        this.age = age;
    }

    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String toString() {
        return "[name:" + this.name + ";age:" + this.age + "]";
    }

    public static void main(String[] args) {
        InstenceOtherClass instenceOtherClass = new InstenceOtherClass("huang", 12);
        System.out.println(instenceOtherClass.toString());//因为重写了toString，所以可以直接输出，否则输出对象
    }
}

class Test {
    public static void main(String[] args) {
        Class<?> clazz = null;
        try {
            clazz = Class.forName("com.huangfu.learning.javabase.java.reflect.InstenceOtherClass");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        InstenceOtherClass instenceOtherClass = null;
        try {
            // 这里注意，无参构造函数必须要，否则报错
            instenceOtherClass = (InstenceOtherClass) clazz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        instenceOtherClass.setAge(22);
        instenceOtherClass.setName("chen");
        System.out.println(instenceOtherClass);
    }
}